#ifndef DDREADWRITEFILE__MYSELF
#define DDREADWRITEFILE__MYSELF


class DDReadWriteFile
{
public:
	DDReadWriteFile()
	{
		m_bRead = TRUE;
		m_hFile = NULL;
		m_llOffset = 0;
	}
	~DDReadWriteFile()
    {
		MySafeCloseHandle(m_hFile);
    }
public:
	void DDCloseFile()
	{
		MySafeCloseHandle(m_hFile);
	}
	int DDCreateFile(char* pFileName,BOOL bRead = TRUE,LONGLONG *pllFileSize = NULL)
	{
		MySafeCloseHandle(m_hFile);
		m_bRead = bRead;
		
		if( m_bRead )
		{
			if( ::GetFileAttributes(pFileName) == 0xffffffff )
			{
				return -1;
			}

			m_hFile = CreateFile((LPCTSTR)pFileName,
		                     GENERIC_READ/*|GENERIC_WRITE*/,
							 FILE_SHARE_READ/*|FILE_SHARE_WRITE*/,
							 NULL,
							 OPEN_ALWAYS,
							 FILE_ATTRIBUTE_NORMAL,
							 NULL
		                    );
		}
		else
		{
			m_hFile = CreateFile((LPCTSTR)pFileName,
		                     /*GENERIC_READ|*/GENERIC_WRITE,
							 FILE_SHARE_READ|FILE_SHARE_WRITE,
							 NULL,
							 OPEN_ALWAYS,
							 FILE_ATTRIBUTE_NORMAL,
							 NULL
		                    );
		}
		
		if(INVALID_HANDLE_VALUE == m_hFile)
		{
			m_hFile = NULL;
			return -1;
		}

		if( NULL != pllFileSize )
		{
			DWORD dwLow,dwHigh = 0;
			LONGLONG llFileSize = 0;
			dwLow = GetFileSize(m_hFile,&dwHigh);
			llFileSize = dwHigh;
			llFileSize <<= 32;
			llFileSize |= dwLow;

			*pllFileSize = llFileSize;
		}

		m_llOffset = 0;
		
		return 0;
	}
	int DDOperatorFile(BYTE*pBuffer,DWORD dwBytesToRead,LONGLONG *pllOffset = NULL,BOOL bRead = TRUE)
	{
		if(NULL == m_hFile || m_bRead != bRead )
		{
			return -1;
		}

		if( NULL != pllOffset )
		{
			m_llOffset = *pllOffset;
		}
		
		DWORD dwBytesOper;
		
		OVERLAPPED OverLapped;
		OverLapped.Offset     = (DWORD)(m_llOffset & 0xffffffff); 
		OverLapped.OffsetHigh = (DWORD)((m_llOffset >> 32) & 0xffffffff);  
		OverLapped.hEvent     = NULL; 

		BOOL bResult = FALSE;
		
		if(bRead)
		{
			bResult= ReadFile(  m_hFile,
								pBuffer,
								dwBytesToRead,
								&dwBytesOper,
								&OverLapped
								); 
		}
		else
		{
			bResult= WriteFile( m_hFile,
								pBuffer,
								dwBytesToRead,
								&dwBytesOper,
								&OverLapped
								); 
		}

		m_llOffset += dwBytesOper;

		if( NULL != pllOffset )
		{
			*pllOffset = m_llOffset;
		}
		
		if(!bResult)
		{
			return -1;
		}

		return 0;
	}
private:
	HANDLE m_hFile;
	BOOL   m_bRead;
	LONGLONG m_llOffset;
};
 

#endif //